package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.IGeneratePageService;
import com.heima.common.exception.CustomizeException;
import com.heima.common.exception.CustomizeExceptionBuilder;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.oss.service.FileStorageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageService implements IGeneratePageService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private ApAuthorMapper apAuthorMapper;
    @Autowired
    @Qualifier("minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${file.minio.prefix}")
    private String prefix;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        log.info("文章静态页生成方法被调用，文章内容: {}, 文章基本信息: {}", content, apArticle);
        //1.准备模板
        try {
            Template template = configuration.getTemplate("article.ftl");
            //2.准备数据(article content)
            Map data = new HashMap();
            data.put("article", apArticle);
            List<Map> contentList = JSON.parseArray(content, Map.class);
            data.put("content", contentList);
            ApAuthor apAuthor = apAuthorMapper.selectById(apArticle.getAuthorId());
            if(apAuthor == null){
                log.error("生成静态页面失败，失败原因: {}, 当前文章 id: {}", "当前文章的作者所对应的APP用户信息不存在", apArticle.getId());
                CustomizeExceptionBuilder.builder(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章的作者所对应的APP用户信息不存在");
            }
            data.put("authorApUserId", apAuthor.getUserId());
            //3.基于 template 替换模板，并输出到指定位置
                //3.1准备字符输出流
            StringWriter stringWriter = new StringWriter();
                //3.2替换模板将替换后的内容输出到字符输出流中
            template.process(data, stringWriter);
                //3.3将字符输出流中的字符串内容封装到字节数组输入流中
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            //4.将输入流所代表的静态页内容输出到 minio 中
                //fileName 选择使用文章 id，区分不同的文章，contentType 需要指定上传文件的 MIME 类型
                //静态页面保存到 minio 中后会返回一个文章在 minio 中的路径
            String storePath = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            //5.修改文章内容(static_url)
            apArticle.setStaticUrl(storePath);
            apArticleMapper.updateById(apArticle);
            log.info("文章静态页面生成成功，文章在 minio 中的资源路径: {}", storePath);
        } catch (IOException | TemplateException e) {
            log.error("文章静态页面生成失败，失败原因: {}", e);
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.SERVER_ERROR, "文章生产静态页面失败");
        }
    }
}
